package com.apes.fn.server.reworkAppraisal.model;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.apes.crm.callCenter.model.CustomComplain;
import com.apes.fn.crm.customComplain.FnCustomComplain;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 功能：返修鉴定单
 *
 * @author wsj
 * @create 2019-12-31 11:23
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ReworkAppraisal.CONST_TABLE_NAME)
public class ReworkAppraisal extends Model {
    public static final String CONST_TABLE_NAME = "fn_rework_appraisal";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "返修鉴定单", padding = 4 , prefix = "JD%(company)%(yy)%(month)", useDateRange = true)
    @Comment("返修鉴定单号")
    private String id;   //单号

    @Column(name = "source_business_type", length = 32, nullable = true)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source", length = 30)
    @Comment("来源单据号码")
    private String source;

    @Column(name = "note", length = 120)
    @Comment("备注")
    private String note; //备注


    @States(name = "订单状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "delete", name = "删除"),
            @State(id = "approve", name = "审核"),
            @State(id = "appraisal", name = "鉴定"),
            @State(id = "dispense", name = "分发"),
            @State(id = "repeal", name = "终止")
    })
    @Column(name = "state", length = 20, nullable = false)
    @Comment("单据状态")
    private String state = "create"; //状态

    @States(name = "返修类型", values = {
            @State(id = "A", name = "正常"),
            @State(id = "B", name = "内部返修"),
            @State(id = "C", name = "外部返修")})
    @Comment("返修类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "rework_type", nullable = false, referencedColumnName = "id")
    private BusinessAttributeValue reworkType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid; //审批人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date approveDate; //审批日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_uid", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "repeal_uid", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole repealUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "repeal_date")
    @Comment("终止日期")
    private Date repealDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apportion_uid", referencedColumnName = "id")
    @Comment("分摊人")
    private PartyRole apportionUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "apportion_date")
    @Comment("分摊日期")
    private Date apportionDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dispense_uid", referencedColumnName = "id")
    @Comment("分发人")
    private PartyRole dispenseUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dispense_date")
    @Comment("分发日期")
    private Date dispenseDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "appraisal_uid", referencedColumnName = "id")
    @Comment("鉴定人")
    private PartyRole appraisalUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "appraisal_date")
    @Comment("鉴定日期")
    private Date appraisalDate;

    @Comment("门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    private Dept dept;

    @Comment("服务门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "serve_dept_id", referencedColumnName = "id")
    private Dept serveDept;

    @Comment("客诉单")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "custom_complain_id", referencedColumnName = "id")
    private FnCustomComplain customComplain;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;


    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }

    @Transient
    private Map customerCar;

    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer()
        );
    }


    @Comment("公司承担金额")
    @Column(name = "company_to_bear",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double companyToBear = 0;

    @Comment("个人承担金额")
    @Column(name = "personal_to_bear", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double personalToBear = 0;

    @Comment("供应商承担金额")
    @Column(name = "supplier_to_bear",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double supplierToBear = 0;

    @Comment("客户承担金额")
    @Column(name = "customer_to_bear",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double customerToBear = 0;

    @Comment("返修服务方案号")
    @Column(name = "rework_serve_plan")
    private String reworkServePlan;

    @Comment("公司编码")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private  PartyRole company;

    @Column(name = "major_rework",nullable = false,columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("重大返修标记")
    private boolean majorRework = false;


    @Comment("故障现象")
    @Column(name = "failure_phenomenon", length = 300)
    private  String failurePhenomenon;


    @OneToMany(mappedBy = "reworkAppraisal", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<ReworkAppraisalItem> reworkAppraisalItems = new HashSet(); //明细

    public Set<ReworkAppraisalItem> getReworkAppraisalItems() {
        for (ReworkAppraisalItem item : reworkAppraisalItems) {
            item.setReworkAppraisal(this);
        }
        return reworkAppraisalItems;
    }


    @Transient
    public JSONObject creatorName;

    public void setCreatorName(JSONObject creatorName){
        return;
    }

    public JSONObject getCreatorName(){
        if (getCreator()==null)return null;
        PartyRole partyRole = SpringManager.getBean(PartyRoleRepository.class).findOne(getCreator());
        JSONObject resultJson = new JSONObject();
        resultJson.put("id",partyRole.getId());
        resultJson.put("name",partyRole.getName());
        return resultJson;

    }

}
